<template>
  <div class="app-container">
    <div class="search">
      <el-form ref="form" :model="search" :inline="true">
        <el-form-item label="设备编号：">
          <el-input
            v-model="search.innerCode"
            clearable
            placeholder="请输入"
            size="medium"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="medium"
            class="my-primary1"
            icon="el-icon-search"
            @click="query"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="result">
      <el-table
        :data="tableData"
        style="width: 100%"
        empty-text="暂无数据"
        fit
        highlight-current-row
        :cell-style="{
          height: '44px',
          padding: '2px 0px',
          textAlign: 'left',
          color: 'rgb(102, 102, 102)',
          borderBottom: 'none',
        }"
        :header-cell-style="{
          lineHeight: 1.15,
          padding: '10px 0px 9px',
          background: 'rgb(243, 246, 251)',
          fontWeight: 500,
          textAlign: 'left',
          color: 'rgb(102, 102, 102)',
          borderBottom: 'none',
        }"
      >
        <el-table-column
          type="index"
          :index="(index) => (search.pageIndex - 1) * 10 + (index + 1)"
          label="序号"
          width="80px"
        />
        <el-table-column prop="innerCode" label="设备编号" />
        <el-table-column prop="type.name" label="设备型号" />
        <el-table-column label="详细地址">
          <template v-slot="{ row }">
            {{ row.node.addr.substring(row.node.addr.lastIndexOf("-") + 1) }}
          </template>
        </el-table-column>
        <el-table-column label="运营状态">
          <template v-slot="{ row }">
            {{
              row.vmStatus === 0
                ? "未投放"
                : row.vmStatus === 1
                  ? "运营"
                  : "撤机"
            }}
          </template>
        </el-table-column>
        <el-table-column label="设备状态" width="300px">
          <template v-slot="{ row }">
            <div class="vm-status">
              <div class="item">
                <div
                  class="success"
                  :class="{ 'offline-danger': !row.status['10001'] }"
                >
                  离线
                </div>
              </div>
              <div class="item">
                <div
                  class="success"
                  :class="{ 'offline-danger': !row.status['10002'] }"
                >
                  货道
                </div>
              </div>
              <div class="item">
                <div
                  class="success"
                  :class="{ 'offline-danger': !row.status['10003'] }"
                >
                  传动轴
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template v-slot="{ row }">
            <el-button
              type="text"
              class="el-button--primary-text"
              @click.native="showVmInfo(row.innerCode)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          layout="slot,prev,next"
          :current-page.sync="search.pageIndex"
          :total="totalCount"
          :page-size="search.pageSize"
          prev-text="上一页"
          next-text="下一页"
          @current-change="vmSearch"
        >
          <template order="-1">
            <span
              class="el-pagination__total"
            >共{{ totalCount }}条记录 第 {{ search.pageIndex }}/{{
              totalPage
            }}
              页</span>
          </template>
        </el-pagination>
      </div>
    </div>
    <el-dialog
      title="设备详情"
      :visible.sync="vmInfoDialog"
      width="630px"
      @close="vmInfoClose"
    >
      <div style="width: 579px; margin: 0px auto">
        <el-row
          type="flex"
          justify="space-around"
          align="middle"
          class="sku-stats"
        >
          <el-col :span="6">
            销售量：
            <span class="number">{{ orderCount }}</span>
            <span class="unit">&nbsp;个</span>
          </el-col>
          <el-col :span="6">
            销售额：
            <span class="number">{{ orderAmount }}</span>
            <span class="unit">&nbsp;万元</span>
          </el-col>
          <el-col :span="6">
            补货次数：
            <span class="number">{{ supplyCount }}</span>
            <span class="unit">&nbsp;次</span>
          </el-col>
          <el-col :span="6">
            维修次数：
            <span class="number">{{ repairCount }}</span>
            <span class="unit">&nbsp;次</span>
          </el-col>
        </el-row>
        <div class="sku-title">商品销量（月）</div>
        <el-row class="sku-list">
          <el-col v-for="item,index in skuCollectList" :key="index" :span="6">
            <el-row class="sku-item">
              <el-col :span="14">
                <div :title="item.skuName" class="sku-name">{{ item.skuName }}</div>
              </el-col>
              <el-col :span="10">：{{ item.count }}</el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { searchVmList } from '@/api/vm'
import { getOrderCount, getOrderAmount, getSkuCollect } from '@/api/order'
import { getRepairCount, getSupplyCount } from '@/api/task'
export default {
  data() {
    return {
      search: {
        innerCode: '',
        status: null,
        pageIndex: 1,
        pageSize: 10
      },
      tableData: [],
      totalCount: 0,
      totalPage: 0,
      vmInfoDialog: false,
      orderCount: 0,
      orderAmount: 0,
      repairCount: 0,
      supplyCount: 0,
      skuCollectList: []
    }
  },
  async created() {
    await this.vmSearch()
  },
  methods: {
    query() {
      this.search.pageIndex = 1
      this.vmSearch()
    },
    async vmSearch() {
      const { currentPageRecords, totalCount, totalPage } = await searchVmList({
        ...this.search
      })
      this.totalCount = parseInt(totalCount)
      this.totalPage = totalPage
      this.tableData = currentPageRecords.map((item) => {
        item.createType = item.createType ? '手动' : '自动'
        item.createTime = this.formattedDate(item.createTime)
        return item
      })
    },
    today() {
      // 获取当前日期字符串
      return new Date()
        .toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        })
        .replace(/\//g, '-')
    },
    firstDayOfMonth() {
      const today = new Date()
      // 获取本月第一天字符串
      return new Date(today.getFullYear(), today.getMonth(), 1)
        .toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        })
        .replace(/\//g, '-')
    },
    formattedDate(date) {
      const currentDate = new Date(date)
      const year = currentDate.getFullYear()
      const month = ('0' + (currentDate.getMonth() + 1)).slice(-2)
      const day = ('0' + currentDate.getDate()).slice(-2)
      const hours = ('0' + currentDate.getHours()).slice(-2)
      const minutes = ('0' + currentDate.getMinutes()).slice(-2)
      const seconds = ('0' + currentDate.getSeconds()).slice(-2)
      return `${year}.${month}.${day} ${hours}:${minutes}:${seconds}`
    },
    async showVmInfo(innerCode) {
      this.vmInfoDialog = true
      this.orderCount = await getOrderCount({
        start: this.firstDayOfMonth() + ' 00:00:00',
        end: this.today() + ' 23:59:59',
        innerCode
      })
      const amount = await getOrderAmount({
        start: this.firstDayOfMonth() + ' 00:00:00',
        end: this.today() + ' 23:59:59',
        innerCode
      })
      this.orderAmount = (amount / 1000000).toFixed(2)
      this.repairCount = await getRepairCount(innerCode, this.firstDayOfMonth(), this.today())
      this.supplyCount = await getSupplyCount(innerCode, this.firstDayOfMonth(), this.today())
      this.skuCollectList = await getSkuCollect(innerCode, this.firstDayOfMonth(), this.today())
    },
    vmInfoClose() {
      this.vmInfoDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/common.scss";
</style>
